package com.xinchuang.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinchuang.comment.KeyWord;
import com.xinchuang.comment.LogConstant;
import com.xinchuang.comment.R;
import com.xinchuang.domain.entity.DictTable;
import com.xinchuang.domain.entity.TestModelMainTable;
import com.xinchuang.domain.entity.TestModelSubTable;
import com.xinchuang.domain.entity.TestNoticeMainTabale;
import com.xinchuang.domain.pojo.TryOutDeviceMod;
import com.xinchuang.domain.type.ModelMainEnum;
import com.xinchuang.domain.vo.TestModelTableVo;
import com.xinchuang.entity.Edtion;
import com.xinchuang.entity.api.ModePlanApi;
import com.xinchuang.entity.api.ModePlanTestApi;
import com.xinchuang.entity.api.OaUserParam;
import com.xinchuang.entity.api.UserApi;
import com.xinchuang.manager.TestModelSubTableService;
import com.xinchuang.manager.TestNoticeMainTabaleService;
import com.xinchuang.manager.impl.TestModelMainTableServiceImpl;
import com.xinchuang.mapper.*;
import com.xinchuang.role.entity.SystemHeader;
import com.xinchuang.service.OaUserService;
import com.xinchuang.service.TryOutPlanModService;
import com.xinchuang.service.actual.EdtionService;
import com.xinchuang.service.apiutil.impl.ApiUtilServiceImpl;
import com.xinchuang.utils.EdtionVerity;
import com.xinchuang.utils.IdUtils;
import com.xinchuang.utils.MyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class TryOutPlanModServiceImpl implements TryOutPlanModService {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private TestModelMainTableServiceImpl testModelMainTableService;

    @Autowired
    private TestModelSubTableService testModelSubTableService;

    @Autowired
    private TestModelMainTableMapper testModelMainTableMapper;

    @Autowired
    private TestNoticeMainTabaleService testNoticeMainTabaleService;

    @Autowired
    private TryOutDeviceModMapper tryOutDeviceModMapper;

    @Autowired
    private DictTableMapper dictTableMapper;

    @Autowired
    private UserApiMapper userApiMapper;

    @Autowired
    private EdtionService edtionService;

    @Autowired
    private KeyWord keyWord;

    @Autowired
    private OaUserService oaUserService;
    @Autowired
    private OaUserMapper oaUserMapper;

    private SnowflakeGenerator snow = new SnowflakeGenerator(0, 0);

    @Override
    public String getNatureWeekList() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> map;
        int number = MyUtils.getWeekNumber() + 6;
        for (int i = number; i >= 1; i--) {
            map = new HashMap<>();
            int year = DateUtil.year(new Date());
            if (number > 53) {
                map.put("weekId", (year + 1) + "-" + (number - 53));
                map.put("weekName", String.format(
                        "第%s周_(%s~%s)",
                        (number - 53),
                        MyUtils.getYearWeekDays((year + 1), (number - 53), 1).substring(0, 10),
                        MyUtils.getYearWeekDays((year + 1), (number - 53), 2).substring(0, 10))
                );
            } else {
                if (number == 53 && MyUtils.getWeekStartDays(number).substring(0, 4).equals((year + 1) + "")) {
                    number -= 1;
                    continue;
                }
                map.put("weekId", year + "-" + number);
                map.put("weekName", String.format(
                        "第%s周_(%s~%s)",
                        number,
                        MyUtils.getWeekStartDays(number).substring(0, 10),
                        MyUtils.getWeekEndDays(number).substring(0, 10))
                );
            }
            resultList.add(map);
            number -= 1;
        }
        return JSON.toJSONString(R.data(resultList));
    }

    @Override
    public R getTryOutPlanList(JSONObject jsonObject) {
        //jsonobject解析获取第几周
        String weekId = jsonObject.getString("weekId");
        //jsonobject解析获取页码
        String pageNum = jsonObject.getString("pageNum");
        //jsonobject解析获取每页数量
        String pageSize = jsonObject.getString("pageSize");
        Page<TestModelMainTable> testModelMainTablePage = new Page<>(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
        LambdaQueryWrapper<TestModelMainTable> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(weekId)) {
            wrapper.eq(TestModelMainTable::getWeekId, weekId);
        }
        wrapper.orderByDesc(TestModelMainTable::getYear);
        wrapper.orderByDesc(TestModelMainTable::getWeek);
        Page<TestModelMainTable> page = testModelMainTableService.page(testModelMainTablePage, wrapper);
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            Map<String, Object> map;
            for (TestModelMainTable record : page.getRecords()) {
                map = new HashMap<>();
                map.put("id", record.getId());
                //计划编制人
                map.put("username", StringUtils.isBlank(record.getPlanAuthor()) ? "" : record.getPlanAuthor());
                //第几周名称
                map.put("weekOfYear", StringUtils.isBlank(record.getWeekOfYear()) ? "" : record.getWeekOfYear());
                //计划状态
                map.put("status", StringUtils.isBlank(record.getStatus()) ? 0 : Integer.valueOf(record.getStatus()));
                //计划编制时间
                map.put("addtime", ObjectUtil.isNull(record.getPlanTime()) ? "" : DateUtil.format(record.getPlanTime(), "yyyy-MM-dd"));
                //试模计划名称
                map.put("planName", StringUtils.isBlank(record.getPlanName()) ? "" : record.getPlanName());
                //编号
                map.put("serialNumber", StringUtils.isBlank(record.getSerialNumber()) ? "" : record.getSerialNumber());
                //版本Id
                map.put("versionId", StringUtils.isBlank(record.getVersion()) ? "" : record.getVersion());
                //版次
                map.put("edition", null == record.getEdition() ? "V1" : "V" + record.getEdition());
                List<Map<String, Object>> planList = new ArrayList<>();
                List<TestModelSubTable> subTables = testModelSubTableService.list(new LambdaQueryWrapper<TestModelSubTable>()
                        .eq(TestModelSubTable::getParentPlanId, record.getId()));
                Map<String, Object> plan;
                if (CollectionUtil.isNotEmpty(subTables)) {
                    for (TestModelSubTable subTable : subTables) {
                        plan = new HashMap<>();
                        //通知单子信息ID
                        plan.put("planId", subTable.getPlanId());
                        //材料名称
                        plan.put("materialName", StringUtils.isBlank(subTable.getMaterialName()) ? "" : subTable.getMaterialName());
                        //材料重量
                        plan.put("materialWeight", StringUtils.isBlank(subTable.getMaterialWeight()) ? "" : subTable.getMaterialWeight());
                        //预计试模时间
                        plan.put("plannedTime", ObjectUtil.isNull(subTable.getPlannedTime()) ? "" : DateUtil.format(subTable.getPlannedTime(), "yyyy-MM-dd"));
                        //实际试模时间
                        plan.put("practicalTime", ObjectUtil.isNull(subTable.getPracticalTime()) ? "" : DateUtil.format(subTable.getPracticalTime(), "yyyy-MM-dd"));
                        //试模设备
                        plan.put("moldTestingDevice", StringUtils.isBlank(subTable.getMoldTestingDevice()) ? "" : subTable.getMoldTestingDevice());
                        //试模次数
                        plan.put("tryOutTimes", StringUtils.isBlank(subTable.getTryOutTimes()) ? "" : "T" + subTable.getTryOutTimes());
                        //试模件数
                        plan.put("tryOutDeviceCount", null == subTable.getTryOutDeviceCount() ? 0 : subTable.getTryOutDeviceCount());
                        //主要联络人Id
                        JSONArray projectManagerId = null;
                        if (StringUtils.isNumeric(subTable.getProjectManagerId()) && StringUtils.isNumeric(subTable.getProjectManagerName())) {
                            projectManagerId = new JSONArray();
                            projectManagerId.add(Integer.valueOf(subTable.getProjectManagerId()));
                            projectManagerId.add(Integer.valueOf(subTable.getProjectManagerName()));
                        }
                        plan.put("projectManagerId", projectManagerId);
                        //备注
                        plan.put("remark", StringUtils.isBlank(subTable.getRemark()) ? "" : subTable.getRemark());
                        //模具编号
                        plan.put("moldId", StringUtils.isBlank(subTable.getMoldId()) ? "" : subTable.getMoldId());
                        //模具名称
                        plan.put("moldName", StringUtils.isBlank(subTable.getMoldName()) ? "" : subTable.getMoldName());
                        //客户
                        plan.put("customerName", StringUtils.isBlank(subTable.getCustomerName()) ? "" : subTable.getCustomerName());
                        //钳工
                        JSONArray tongmanName = null;
                        if (StringUtils.isNumeric(subTable.getTongmanId()) && StringUtils.isNumeric(subTable.getTongmanName())) {
                            tongmanName = new JSONArray();
                            tongmanName.add(Integer.valueOf(subTable.getTongmanId()));
                            tongmanName.add(Integer.valueOf(subTable.getTongmanName()));
                        }
                        plan.put("tongmanName", tongmanName);
                        //项目名称
                        plan.put("projectName", StringUtils.isBlank(subTable.getProjectName()) ? "" : subTable.getProjectName());
                        //模具要求完成时间
                        plan.put("requiredTime", StringUtils.isBlank(subTable.getRequiredTime()) ? "" : subTable.getRequiredTime());
                        //烘料要求
                        plan.put("bakingMaterialsRequirements", StringUtils.isBlank(subTable.getBakingMaterialsRequirements()) ? "" : subTable.getBakingMaterialsRequirements());
                        //试模台时费（元/小时）
                        plan.put("price", StringUtils.isBlank(subTable.getPrice()) ? "" : subTable.getPrice());
                        //模具试模地址
                        plan.put("tryOutAddress", StringUtils.isBlank(subTable.getTryOutAddress()) ? "" : subTable.getTryOutAddress());
                        //模具定模重量
                        plan.put("dingmoWeight", StringUtils.isBlank(subTable.getDingmoWeight()) ? "" : subTable.getDingmoWeight());
                        //模具动模重量
                        plan.put("dongmoWeight", StringUtils.isBlank(subTable.getDongmoWeight()) ? "" : subTable.getDongmoWeight());
                        //模具动作注意事项
                        plan.put("moldActionPrecautions", StringUtils.isBlank(subTable.getMoldActionPrecautions()) ? "" : subTable.getMoldActionPrecautions());
                        //试模目的
                        plan.put("targetId", StringUtils.isBlank(subTable.getTargetId()) ? "" : subTable.getTargetId());
                        //试模原因
                        plan.put("tryOutReasonId", StringUtils.isBlank(subTable.getTryOutReasonId()) ? "" : subTable.getTryOutReasonId());
                        //外观要求
                        plan.put("surface", StringUtils.isBlank(subTable.getSurface()) ? "" : subTable.getSurface());
                        planList.add(plan);
                    }
                }
                map.put("planList", planList);
                resultList.add(map);
            }
        }
        HashMap<String, Object> data = new HashMap<>();
        data.put("dataList", resultList);
        data.put("totalNum", page.getTotal());
        return R.data(data);
    }

    @Override
    @Transactional
    public String addTryOutPlan(JSONObject jsonObject, HttpServletRequest request, boolean isUpdate) {
        //jsonobject解析获取第几周名称
        String weekOfYear = jsonObject.getString("weekOfYear");
        //jsonobject解析获取周ID
        String weekId = jsonObject.getString("weekId");
        //jsonobject解析获取名称
        String planName = jsonObject.getString("planName");
        //jsonobject解析获取编号
        String serialNumber = jsonObject.getString("serialNumber");
        //jsonobject解析获取版本Id
        String version = jsonObject.getString("version");
        //jsonobject解析获取计划列表（数组）
        JSONArray dataList = jsonObject.getJSONArray("dataList");
        String mainId;
        if (isUpdate) {
            mainId = jsonObject.getString("id");
        } else {
            mainId = IdUtils.simpleUUID();
        }
        UserApi userApi = userApiMapper.selectById(MyUtils.getHeader(request).getId());
        TestModelMainTable testModelMainTable = new TestModelMainTable(
                mainId,
                planName,
                serialNumber,
                version,
                new Date(),
                new Date(),
                weekId,
                weekOfYear,
                userApi.getName(),
                ModelMainEnum.CREATE_PLAN.getCode(),
                new Date(),
                new Date(),
                1
        );
        testModelMainTable.setYear(Integer.valueOf(weekId.split("-")[0]));
        testModelMainTable.setWeek(Integer.valueOf(weekId.split("-")[1]));
        try {
            List<TestModelSubTable> testModelSubTables = JSONArray.parseArray(dataList.toJSONString(), TestModelSubTable.class);
            for (TestModelSubTable testModelSubTable : testModelSubTables) {
                if (StringUtils.isNotBlank(testModelSubTable.getTryOutTimes())) {
                    if (!testModelSubTable.getTryOutTimes().toUpperCase().contains("T")
                            || !StringUtils.isNumeric(testModelSubTable.getTryOutTimes().toUpperCase().split("T")[1])) {
                        return JSON.toJSONString(R.fail("请确认模具状态,填写是否为T+数字的格式,如:T0、T1等"));
                    }
                    testModelSubTable.setTryOutTimes(testModelSubTable.getTryOutTimes().toUpperCase().split("T")[1]);
                } else {
                    testModelSubTable.setTryOutTimes(null);
                }
                if (StringUtils.isNotEmpty(testModelSubTable.getPlanId())) {
                    testModelSubTable.setPlanId(IdUtils.simpleUUID());
                }
                testModelSubTable.setParentPlanId(mainId);
                testModelSubTable.setCreateTime(new Date());
                testModelSubTable.setUpdateTime(new Date());
                if (CollectionUtil.isNotEmpty(testModelSubTable.getTongmanArray())) {
                    JSONArray array = testModelSubTable.getTongmanArray();
                    testModelSubTable.setTongmanId(array.getString(0));
                    testModelSubTable.setTongmanName(array.getString(1));
                }
                if (CollectionUtil.isNotEmpty(testModelSubTable.getProjectManagerArray())) {
                    JSONArray array = testModelSubTable.getProjectManagerArray();
                    testModelSubTable.setProjectManagerId(array.getString(0));
                    testModelSubTable.setProjectManagerName(array.getString(1));
                }
                //前端传过来的是字典id，转换成字典名称 -> 客户名称
                if (StringUtils.isNotBlank(testModelSubTable.getCustomerName())) {
                    DictTable customerDictTable = dictTableMapper.selectOne(new LambdaQueryWrapper<DictTable>()
                            .eq(DictTable::getDicId, testModelSubTable.getCustomerName()).last("LIMIT 1"));
                    if (Objects.nonNull(customerDictTable)) {
                        testModelSubTable.setCustomerName(customerDictTable.getDicName());
                    }
                }
            }
            testModelMainTableService.saveOrUpdate(testModelMainTable);
            testModelSubTableService.saveOrUpdateBatch(testModelSubTables);
        } catch (NumberFormatException e) {
            return JSON.toJSONString(R.fail("请确认试模次数/试模件数,填写是否为数字格式"));
        }
        return JSON.toJSONString(R.success("保存成功"));
    }

    @Override
    public synchronized String changeTryOutPlan(JSONObject jsonObject, HttpServletRequest request, Integer userId) {
        //jsonobject解析获取试模计划Id
        String planId = jsonObject.getString("planId");
        TestModelMainTable modelMainTable = testModelMainTableMapper.selectById(planId);
        if (Objects.isNull(modelMainTable)) {
            return JSON.toJSONString(R.fail("试模计划不存在/已删除"));
        } else if (modelMainTable.getStatus().equals(ModelMainEnum.PLAN_DONE.getCode())) {
            return JSON.toJSONString(R.fail("该计划已提交过"));
        }
        TestModelTableVo testModelTableVos = testModelMainTableMapper.editTryOutPlan(planId);
        String parentPlanId = testModelTableVos.getId();
        List<TestModelSubTable> modelSubTables = testModelSubTableService.lambdaQuery().eq(TestModelSubTable::getParentPlanId, modelMainTable.getId()).list();
        if (CollectionUtil.isEmpty(modelSubTables)) {
            return JSON.toJSONString(R.fail("该计划暂无通知单，请填写后在提交"));
        } else {
            for (TestModelSubTable modelSubTable : modelSubTables) {
                if (!StringUtils.isNumeric(modelSubTable.getTongmanId()) || !StringUtils.isNumeric(modelSubTable.getTongmanName())) {
                    return JSON.toJSONString(R.fail("该计划表中，有钳工暂未填写，请检查后重试"));
                }
                if (!StringUtils.isNumeric(modelSubTable.getProjectManagerId()) || !StringUtils.isNumeric(modelSubTable.getProjectManagerName())) {
                    return JSON.toJSONString(R.fail("该计划表中，有项目联系人暂未填写，请检查后重试"));
                }
            }
        }

        if (Objects.isNull(userId)) {
            SystemHeader header = MyUtils.getHeader(request);
            OaUserParam oaUserParam = oaUserMapper.selectOne(new LambdaQueryWrapper<OaUserParam>().eq(OaUserParam::getUsername, header.getUserName()));
            userId = oaUserParam.getId();
        }
        //OA系统提交工单
        boolean applyToTryOut = applyToTryOut(modelMainTable, modelSubTables, userId);
        log.info("计划表工单提交状态：" + applyToTryOut);
        if (applyToTryOut) {
            modelMainTable.setStatus(ModelMainEnum.PLAN_DONE.getCode());
            modelMainTable.setEdition(1);
            testModelMainTableMapper.updateById(modelMainTable);
            //本地数据操作
            List<TestModelSubTable> dataList = testModelTableVos.getDataList();
            ArrayList<TestNoticeMainTabale> TestNoticeMainTabales = new ArrayList<>();

            for (TestModelSubTable testModelSubTable : dataList) {
                UserApi userApi = null;
                if (StringUtils.isNotBlank(testModelSubTable.getProjectManagerName())) {
                    userApi = userApiMapper.selectOne(
                            new LambdaQueryWrapper<UserApi>()
                                    .eq(UserApi::getId, testModelSubTable.getProjectManagerName())
                                    .last("LIMIT 1")
                    );
                    if (ObjectUtil.isNull(userApi)) {
                        OaUserParam userParam = oaUserService.getById(testModelSubTable.getProjectManagerName());
                        userApi = MyUtils.createUserApi(userParam.getName(), userParam.getUsername(), userParam.getId());
                        userApiMapper.insert(userApi);
                    }
                    userId = userApi.getUserId();
                }
                TestNoticeMainTabale testNoticeMainTabale = new TestNoticeMainTabale(
                        snow.next().toString(),
                        parentPlanId,
                        testModelSubTable.getPlanId(),
                        testModelSubTable.getMoldName() + "_T" + testModelSubTable.getTryOutTimes() + "_试模通知单",
                        testModelTableVos.getSerialNumber(),
                        null,
                        testModelSubTable.getTargetId(),
                        null,
                        testModelSubTable.getTryOutReasonId(),
                        null,
                        null,
                        ObjectUtil.isNull(userApi) ? "" : userApi.getName(),
                        null,
                        null,
                        "0",
                        testModelSubTable.getTryOutAddress(),
                        null,
                        testModelSubTable.getMoldTestingDevice(),
                        testModelSubTable.getProjectName(),
                        new Date(),
                        new Date(),
                        null,
                        null,
                        null,
                        userId
                );
                TestNoticeMainTabales.add(testNoticeMainTabale);
            }
            boolean b = testNoticeMainTabaleService.saveBatch(TestNoticeMainTabales);
            if (b) {
                return JSON.toJSONString(R.success("保存成功"));
            }
        }
        return JSON.toJSONString(R.fail(LogConstant.DEFAULT_FAILURE_MESSAGE));
    }

    private boolean applyToTryOut(TestModelMainTable mainTable, List<TestModelSubTable> subTables, Integer userId) {
        ModePlanApi modePlanApi = new ModePlanApi();
        //表头信息
        int week, year;
        if (mainTable.getWeekId().contains("-")) {
            week = MyUtils.getInteger(mainTable.getWeekId().split("-")[1]);
            year = MyUtils.getInteger(mainTable.getWeekId().split("-")[0]);
            modePlanApi.setWeekNumber(MyUtils.getInteger(mainTable.getWeekId().split("-")[1]));
        } else {
            year = DateUtil.year(new Date());
            week = MyUtils.getInteger(mainTable.getWeekId());
            modePlanApi.setWeekNumber(MyUtils.getInteger(mainTable.getWeekId()));
        }
        modePlanApi.setBegin(week > 0 ? MyUtils.dataToIso8601(MyUtils.getWeekToDate(year, week, 1)) : "");
        modePlanApi.setEnd(week > 0 ? MyUtils.dataToIso8601(MyUtils.getWeekToDate(year, week, 2)) : "");
        OaUserParam oaUserParam = oaUserService.getById(userId);
        modePlanApi.setSenderLoginName(oaUserParam.getOaUsername());
        //表单信息
        List<ModePlanTestApi> moulds = new ArrayList<>();
        ModePlanTestApi testApi;
        for (TestModelSubTable subTable : subTables) {
            testApi = new ModePlanTestApi();
            testApi.setProjectName(MyUtils.getStringToStr(subTable.getProjectName()));
            testApi.setMouldNumber(MyUtils.getStringToStr(subTable.getMoldId()));
            OaUserParam pmId = oaUserService.getById(subTable.getProjectManagerName());
            testApi.setProjectManagerOAId(pmId.getOaId());
            testApi.setMouldName(MyUtils.getStringToStr(subTable.getMoldName()));
            testApi.setClient(MyUtils.getStringToStr(subTable.getCustomerName()));
            OaUserParam tgId = oaUserService.getById(subTable.getTongmanName());
            testApi.setFitterOAId(tgId.getOaId());
            Date date = MyUtils.stringToDate(subTable.getRequiredTime());
            if (null != date) {
                testApi.setMouldRequiredCompletionTime(MyUtils.dataToIso8601(date));
            } else {
                testApi.setMouldRequiredCompletionTime("无");
            }
            DictTable dictTable = dictTableMapper.selectOne(new LambdaUpdateWrapper<DictTable>()
                    .eq(DictTable::getTypeName, "试模目的")
                    .eq(DictTable::getDicId, subTable.getTargetId())
                    .last("LIMIT 1")
            );
            if (ObjectUtil.isNotNull(dictTable)) {
                testApi.setMouldTestingPurpuse(MyUtils.getStringToStr(dictTable.getDicName()));
            } else {
                testApi.setMouldTestingPurpuse("无");
            }
            testApi.setMaterial(MyUtils.getStringToStr(subTable.getMaterialName()));
            testApi.setDryingMaterialRequirements(MyUtils.getStringToStr(subTable.getBakingMaterialsRequirements()));
            TryOutDeviceMod deviceMod = tryOutDeviceModMapper.selectOne(new LambdaUpdateWrapper<TryOutDeviceMod>()
                    .eq(TryOutDeviceMod::getDeviceId, subTable.getMoldTestingDevice())
                    .last("LIMIT 1")
            );
            if (ObjectUtil.isNotEmpty(deviceMod)) {
                testApi.setMouldTestingMachine(MyUtils.getStringToStr(deviceMod.getDeviceName()));
            } else {
                testApi.setMouldTestingMachine("无");
            }
            testApi.setPlanTestingDate(MyUtils.dataToIso8601(subTable.getPlannedTime()));
            if (StringUtils.isNotBlank(subTable.getTryOutAddress())) {
                DictTable table = dictTableMapper.selectById(subTable.getTryOutAddress());
                testApi.setMouldTestingLocation(null == table ? "无" : MyUtils.getStringToStr(table.getDicName()));
            } else {
                testApi.setMouldTestingLocation("无");
            }
            testApi.setMouldTestingStage("T" + subTable.getTryOutTimes());
            testApi.setSampleQuantity(null != subTable.getTryOutDeviceCount() ? subTable.getTryOutDeviceCount() : 0);
            testApi.setFixedHalfWeight(MyUtils.getDoubleByString(subTable.getDingmoWeight()));
            testApi.setMovingHalfWeight(MyUtils.getDoubleByString(subTable.getDongmoWeight()));
            String mouldTestingReason = "无";
            dictTable = dictTableMapper.selectOne(new LambdaUpdateWrapper<DictTable>()
                    .eq(DictTable::getTypeName, "试模原因")
                    .eq(DictTable::getDicId, subTable.getTryOutReasonId())
                    .last("LIMIT 1")
            );
            if (ObjectUtil.isNotNull(dictTable)) {
                mouldTestingReason = MyUtils.getStringToStr(dictTable.getDicName());
            }
            testApi.setMouldTestingReason(mouldTestingReason);
            testApi.setAppearanceRequirements(MyUtils.getStringToStr(subTable.getSurface()));
            testApi.setRemarks(MyUtils.getStringToStr(subTable.getRemark()));
            moulds.add(testApi);
        }
        modePlanApi.setMoulds(moulds);
        try {
            HttpResponse login = ApiUtilServiceImpl.login(keyWord.getApi());
            if (login.getStatus() != org.springframework.http.HttpStatus.OK.value()) {
                return false;
            }
            JSONObject json = new JSONObject();
            json.put("weekNumber", modePlanApi.getWeekNumber());
            json.put("begin", modePlanApi.getBegin());
            json.put("end", modePlanApi.getEnd());
            json.put("senderLoginName", modePlanApi.getSenderLoginName());
            json.put("moulds", modePlanApi.getMoulds());
            log.info("向OA系统发送计划表：" + json.toJSONString());
            HttpResponse httpResponse = ApiUtilServiceImpl.
                    doPost(keyWord.getApi() + ApiUtilServiceImpl.CREATE_PLAN, json, login.body());
            log.info("向OA系统发送计划表,返回状态：" + httpResponse.getStatus());
            log.info("向OA系统发送计划表,返回参数：" + httpResponse.body());
            if (httpResponse.getStatus() == HttpStatus.HTTP_OK) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public R editTryOutPlan(JSONObject jsonObject) {
        //jsonobject解析获取计划Id
        String planId = jsonObject.getString("planId");
        TestModelTableVo testModelTableVos = testModelMainTableMapper.editTryOutPlan(planId);
        if (ObjectUtil.isNotEmpty(testModelTableVos)) {
            for (TestModelSubTable subTable : testModelTableVos.getDataList()) {
                if (StringUtils.isNotBlank(subTable.getTongmanId())) {
                    JSONArray array = new JSONArray();
                    array.add(subTable.getTongmanId());
                    array.add(subTable.getTongmanName());
                    subTable.setTongmanArray(array);
                    subTable.setTongmanNameName(oaUserService.getOaUserName(subTable.getTongmanName()));
                } else {
                    subTable.setTongmanArray(new JSONArray());
                }
                if (StringUtils.isNotBlank(subTable.getProjectManagerId())) {
                    JSONArray array = new JSONArray();
                    array.add(subTable.getProjectManagerId());
                    array.add(subTable.getProjectManagerName());
                    subTable.setProjectManagerArray(array);
                    subTable.setProjectManagerNameName(oaUserService.getOaUserName(subTable.getProjectManagerName()));
                } else {
                    subTable.setTongmanArray(new JSONArray());
                }
            }
        }
        return R.data(testModelTableVos);
    }

    @Override
    @Transactional
    public String deleteTryOutPlan(JSONObject jsonObject) {
        //jsonobject解析获取试模计划Id
        String planId = jsonObject.getString("planId");
        testModelMainTableService.removeById(planId);
        LambdaQueryWrapper<TestModelSubTable> testModelSubTableLambdaQueryWrapper = new LambdaQueryWrapper<>();
        testModelSubTableLambdaQueryWrapper.eq(TestModelSubTable::getParentPlanId, planId);
        testModelSubTableService.remove(testModelSubTableLambdaQueryWrapper);
        return JSON.toJSONString(R.success("删除成功"));
    }

    @Override
    @Transactional
    public synchronized String saveTryOutPlan(JSONObject jsonObject, HttpServletRequest request) {
        //jsonobject解析获取计划列表（数组）
        JSONArray dataList = jsonObject.getJSONArray("dataList");
        //jsonobject解析获取周Id
        String weekId = jsonObject.getString("weekId");
        //jsonobject解析获取第几周名称
        String weekOfYear = jsonObject.getString("weekOfYear");
        //jsonobject解析获取名称
        String planName = jsonObject.getString("planName");
        //jsonobject解析获取编号
        String serialNumber = jsonObject.getString("serialNumber");
        //jsonobject解析获取版本
        String version = jsonObject.getString("version");
        //jsonobject解析获取计划Id
        String id = jsonObject.getString("id");
        try {
            TestModelMainTable testModelMainTable = testModelMainTableService.getById(id);
            if (ObjectUtil.isNull(testModelMainTable)) {
                return addTryOutPlan(jsonObject, request, true);
            }
            if (testModelMainTable.getStatus().equals(ModelMainEnum.PLAN_DONE.getCode())) {
                return JSON.toJSONString(R.fail("试模计划已提交，不可修改"));
            }
            if (null == testModelMainTable.getEdition()) {
                testModelMainTable.setEdition(1);
            }
            List<TestModelSubTable> testModelSubTables = JSONArray.parseArray(
                    dataList.toJSONString(),
                    TestModelSubTable.class
            );
            //校验
            SystemHeader header = MyUtils.getHeader(request);
            int i = verityTestModelSubTables(
                    testModelMainTable.getId(),
                    version,
                    planName,
                    serialNumber,
                    header.getId(),
                    testModelMainTable,
                    testModelSubTables
            );
            //更新判断
            if (StringUtils.isNotEmpty(weekId)) {
                testModelMainTable.setWeekId(weekId);
            }
            if (StringUtils.isNotEmpty(weekOfYear)) {
                testModelMainTable.setWeekOfYear(weekOfYear);
            }
            if (StringUtils.isNotEmpty(planName)) {
                testModelMainTable.setPlanName(planName);
            }
            if (StringUtils.isNotEmpty(serialNumber)) {
                testModelMainTable.setSerialNumber(serialNumber);
            }
            if (StringUtils.isNotEmpty(version)) {
                testModelMainTable.setVersion(version);
            }
            if (CollectionUtil.isNotEmpty(testModelSubTables)) {
                testModelSubTableService.remove(new LambdaQueryWrapper<TestModelSubTable>()
                        .eq(TestModelSubTable::getParentPlanId, testModelMainTable.getId()));
                for (TestModelSubTable testModelSubTable : testModelSubTables) {
                    if (StringUtils.isNotBlank(testModelSubTable.getTryOutTimes())) {
                        if (!testModelSubTable.getTryOutTimes().toUpperCase().contains("T")
                                || !StringUtils.isNumeric(testModelSubTable.getTryOutTimes().toUpperCase().split("T")[1])) {
                            return JSON.toJSONString(R.fail("请确认模具状态,填写是否为T+数字的格式,如:T0、T1等"));
                        }
                        testModelSubTable.setTryOutTimes(testModelSubTable.getTryOutTimes().toUpperCase().split("T")[1]);
                    }
                    if (CollectionUtil.isNotEmpty(testModelSubTable.getTongmanArray())) {
                        JSONArray array = testModelSubTable.getTongmanArray();
                        testModelSubTable.setTongmanId(array.getString(0));
                        testModelSubTable.setTongmanName(array.getString(1));
                    }
                    if (CollectionUtil.isNotEmpty(testModelSubTable.getProjectManagerArray())) {
                        JSONArray array = testModelSubTable.getProjectManagerArray();
                        testModelSubTable.setProjectManagerId(array.getString(0));
                        testModelSubTable.setProjectManagerName(array.getString(1));
                    }
                }
            } else {
                testModelSubTableService.remove(new LambdaQueryWrapper<TestModelSubTable>().eq(TestModelSubTable::getParentPlanId, testModelMainTable.getId()));
            }
            if (i > 0) {
                testModelMainTable.setEdition(testModelMainTable.getEdition() + 1);
            }
            testModelMainTableService.saveOrUpdate(testModelMainTable);
            testModelSubTableService.saveOrUpdateBatch(testModelSubTables);
        } catch (NumberFormatException e) {
            return JSON.toJSONString(R.fail("请确认试模次数/试模件数,填写是否为数字格式"));
        }
        return JSON.toJSONString(R.success("保存成功"));
    }

    @Override
    public String getMoldTryOutTimes(JSONObject jsonObject, HttpServletRequest request) {
        //jsonobject解析获取模具id
        String moldId = jsonObject.getString("moldId");
        List<TestModelSubTable> list = testModelSubTableService.lambdaQuery().eq(TestModelSubTable::getMoldId, moldId).list();
        String moldTryOutTimes = "";
        if (Objects.nonNull(list) && !list.isEmpty()) {
            moldTryOutTimes = list.stream()
                    .filter(x -> StringUtils.isNotBlank(x.getTryOutTimes()))
                    .mapToInt(x -> Integer.parseInt(x.getTryOutTimes()))
                    .distinct()
                    .sorted()
                    .mapToObj(String::valueOf)
                    .collect(Collectors.joining(","));
        }
        return JSON.toJSONString(R.data(moldTryOutTimes));
    }

    private int verityTestModelSubTables(
            String parentId,
            String version,
            String planName,
            String serialNumber,
            String userId,
            TestModelMainTable testModelMainTable,
            List<TestModelSubTable> testModelSubTables
    ) {
        List<Edtion> list = new ArrayList<>();
        String oldVersion = null;
        String newVersion = null;
        if (StringUtils.isNotBlank(version) && !version.equals(testModelMainTable.getVersion())) {
            DictTable dictTable = dictTableMapper.selectById(version);
            if (ObjectUtil.isNotNull(dictTable)) {
                newVersion = dictTable.getDicName();
            }
            if (StringUtils.isNotBlank(testModelMainTable.getVersion())) {
                DictTable dictTable1 = dictTableMapper.selectById(testModelMainTable.getVersion());
                if (ObjectUtil.isNotNull(dictTable1)) {
                    oldVersion = dictTable1.getDicName();
                }
            }
        }
        List<Edtion> edtions1 = EdtionVerity.updateMoldPlanMain(testModelMainTable, planName, serialNumber, oldVersion, newVersion, userId);
        if (CollectionUtil.isNotEmpty(edtions1)) {
            list.addAll(edtions1);
        }
        if (CollectionUtil.isNotEmpty(testModelSubTables)) {
            List<String> ids = new ArrayList<>();
            List<String> newIds = new ArrayList<>();
            Map<String, TestModelSubTable> maps = new HashMap<>();
            for (TestModelSubTable sub : testModelSubTables) {
                sub.setParentPlanId(parentId);
                if (StringUtils.isBlank(sub.getPlanId()) || "0".equals(sub.getPlanId())) {
                    sub.setPlanId(snow.next().toString());
                    Edtion edtion = new Edtion();
                    edtion.setRed_id(testModelMainTable.getId());
                    edtion.setEdition("V" + (testModelMainTable.getEdition() + 1));
                    edtion.setKeyValue("通知单模具工号");
                    edtion.setUpdateValue(sub.getMoldId());
                    edtion.setPerson(userId);
                    list.add(edtion);
                } else {
                    ids.add(sub.getPlanId());
                    maps.put(sub.getPlanId(), sub);
                }
            }
            if (ids.size() > 0) {
                for (String id : ids) {
                    TestModelSubTable old = testModelSubTableService.getById(id);
                    if (ObjectUtil.isNull(old)) {
                        continue;
                    }
                    TestModelSubTable newData = maps.get(id);
                    String oldDevice = null;
                    String newDevice = null;
                    String oldTarget = null;
                    String newTarget = null;
                    if (StringUtils.isNotBlank(newData.getMoldTestingDevice()) && !newData.getMoldTestingDevice().equals(old.getMoldTestingDevice())) {
                        TryOutDeviceMod deviceMod = tryOutDeviceModMapper.selectById(newData.getMoldTestingDevice());
                        if (ObjectUtil.isNotNull(deviceMod)) {
                            newDevice = deviceMod.getDeviceName();
                        }
                        if (StringUtils.isNotBlank(old.getMoldTestingDevice())) {
                            TryOutDeviceMod deviceMod1 = tryOutDeviceModMapper.selectById(old.getMoldTestingDevice());
                            if (ObjectUtil.isNotNull(deviceMod1)) {
                                oldDevice = deviceMod1.getDeviceName();
                            }
                        }
                    }
                    if (StringUtils.isNotBlank(newData.getTargetId()) && !newData.getTargetId().equals(old.getTargetId())) {
                        DictTable dictTable = dictTableMapper.selectById(newData.getTargetId());
                        if (ObjectUtil.isNotNull(dictTable)) {
                            newTarget = dictTable.getDicName();
                        }
                        if (StringUtils.isNotBlank(old.getTargetId())) {
                            DictTable dictTable1 = dictTableMapper.selectById(old.getTargetId());
                            if (ObjectUtil.isNotNull(dictTable1)) {
                                oldTarget = dictTable1.getDicName();
                            }
                        }
                    }
                    List<Edtion> edtions = EdtionVerity.verityTestMoldSubTable(old, newData, testModelMainTable.getEdition(), userId, oldDevice, newDevice, oldTarget, newTarget);
                    if (CollectionUtil.isNotEmpty(edtions)) {
                        list.addAll(edtions);
                    }
                }
            }
            List<TestModelSubTable> subTables = testModelSubTableService
                    .lambdaQuery()
                    .eq(TestModelSubTable::getParentPlanId, testModelMainTable.getId())
                    .notIn(CollectionUtil.isNotEmpty(ids), TestModelSubTable::getPlanId, ids)
                    .list();
            if (CollectionUtil.isNotEmpty(subTables)) {
                for (TestModelSubTable subTable : subTables) {
                    Edtion edtion = new Edtion();
                    edtion.setRed_id(testModelMainTable.getId());
                    edtion.setEdition("V" + (testModelMainTable.getEdition() + 1));
                    edtion.setKeyValue("删除");
                    edtion.setBaseValue(subTable.getMoldId());
                    edtion.setPerson(userId);
                    list.add(edtion);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(list)) {
            edtionService.saveBatch(list);
            return 1;
        }
        return 0;
    }

}
